package com.neo.web;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;


@Controller
public class FileUploadController {

    /*@Value("${upload.path}")
    private String uploadPath;

    @GetMapping("/")
    public String index() {
        return "uploadForm";
    }

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:/";
        }

        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(uploadPath + file.getOriginalFilename());
            //Files.copy(bytes, path, StandardCopyOption.REPLACE_EXISTING);
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "Failed to upload file '" + file.getOriginalFilename() + "'");
        }

        return "redirect:/";
    }*/
     /*
    // 可选：提供文件下载功能
    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
        //Resource file = ...; // 从uploadPath获取Resource
        Resource file = getResource(filename); // 从uploadPath获取Resource
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
                .body(file);
    }*/

    @Value("${upload.path}")
    private String uploadPath;

    @PostMapping("/upload")
    public String handleFileUpload(HttpServletRequest request,
                                   RedirectAttributes redirectAttributes) throws IOException {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file"); // 假设表单中的文件字段名为"file"

        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:uploadStatus";
        }

        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(uploadPath + file.getOriginalFilename());
            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");
            //redirectAttributes.addFlashAttribute("message", "文件上传成功!"); // 添加Flash属性
        } catch (IOException e) {
            e.printStackTrace();
        }

        //return "redirect:/uploadStatus";
        return "redirect:/uploadStatus?message=文件上传成功!";
    }

    @GetMapping("/uploadStatus")
    public String showUploadStatus(@RequestParam(required = false) String message, Model model) {
        if (message != null) {
            model.addAttribute("message", message);
        }else{
            model.addAttribute("message", "没有消息");
        }
        return "uploadStatus";
    }
}
